//
//  AfanUserAccount.swift
//  weiboOfAfan
//
//  Created by afan on 16/3/23.
//  Copyright © 2016年 阿范. All rights reserved.
//

import UIKit

class AfanUserAccount: NSObject,NSCoding {
    ///接口获取授权后的access token
    var access_token: String?
    ///可使用的时长
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    ///把可使用的时长,转换为过期时间
    var expiresDate: NSDate?
    
    ///当前授权用户的 UID
    var uid: String?
    
    ///用户名称
    var screen_name : String?
    
    ///用户头像地址
    var avatar_large : String?
    
    
    
    ///kvc 字典转模型
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        ///该办法防止越界   字典中的key在模型中找不到对应的属性
        print("forUndefinedKey: \(key)")
    }
    
    /// 对象打印
    override var description: String {
        // 只读计算性属性
        get {
            let keys = ["access_token", "expires_in", "expiresDate", "uid"]
            // 拿着传入的key去模型中找对应的属性,找到属性的值后会将key和属性的值,拼接成字典
            return dictionaryWithValuesForKeys(keys).description
            //            return "access_token: \(access_token), expires_in: \(expires_in), uid: \(uid)"
        }
    }
    
    //MARK:归档与解档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init()
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large")  as? String
    }
}
